function $(id){
	return document.getElementById(id);
}

var w, h, bg, canvas, ctx1, ctx2;
var direction = 0;//控制方向
w = $('wrap').offsetWidth;
h = $('wrap').offsetHeight;
bg = $('bg');
bg.width = w;
bg.height = h;
canvas = $('canvas');
canvas.width = canvas.height = 50;
canvas.style.top = '50px';
canvas.style.left = '50px';
ctx1 = bg.getContext('2d');
ctx2 = canvas.getContext('2d');

/*初始化背景*/
function initBg(){
	for(var i = 1; i <= 11; i++){
		ctx1.fillText(i, 25, 50*i+25);
		ctx1.fillText(i, 50*i+25, 25);
		ctx1.beginPath();
		ctx1.moveTo(50, 50*i);
		ctx1.lineTo(550, 50*i);
		ctx1.stroke();
		ctx1.beginPath();
		ctx1.moveTo(50*i, 50);
		ctx1.lineTo(50*i, 550);
		ctx1.stroke();
	}
}
initBg();

/*初始化小方块*/
function draw(){
	var bg = ctx2.createLinearGradient(0,0,0,50);
	bg.addColorStop(0, 'blue');
	bg.addColorStop(0.2, 'blue');
	bg.addColorStop(0.2, 'red');
	bg.addColorStop(1, 'red');
	ctx2.fillStyle = bg;
	ctx2.fillRect(0,0,50,50);
}
draw();
/*旋转*/
function rotate( angle){
	var a = canvas.style.transform.match(/\((\d+)deg/);
	if(a == null)
		a = 0;
	else
		a = +a[1];
	canvas.style.transform = 'rotate('+ (a+angle) +'deg)';
}

/*前进*/
function go(number){
	var top = parseInt(canvas.style.top);
	var left = parseInt(canvas.style.left);
	switch(number){
		case 0:
			if(top > 50){
				canvas.style.top = top-50 + 'px';
			}
			break;
		case 1:
			if(left < 500){
				canvas.style.left = left+50 + 'px';
			}
			break;
		case 2:
			if(top < 500){
				canvas.style.top = top+50 + 'px';
			}
			break;
		case 3:
			if(left > 50){
				canvas.style.left = left-50 + 'px';
			}
			break;
	}
}

/*执行*/
$('btn').onclick = function(){
	var value = $('input').value.toLowerCase();
	switch(value){
		case 'go':
			switch(direction){
				case 0: go(0);break;
				case 1: go(1);break;
				case 2: go(2);break;
				case 3: go(3);break;
			}
			break;
		case 'tun lef': 
			rotate(270);
			direction = (direction+3)%4;
			break;
		case 'tun rig': 
			rotate(90);
			direction = (direction+1)%4;
			break;
		case 'tun bac': 
			rotate(180);
			direction = (direction+2)%4;
			break;
	}
};